package com.feng.util;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

/**
 * 引入类包dom4j-1.6.jar文件，另外还有一个jaxen-1.1-beta-4.jar文件，一般也需要引入，
 * 否则执行时可能抛java.lang.NoClassDefFoundError: org/jaxen/JaxenException异常，其他的包可以选择用之
 * */
public class ReadXml {
	
	/**
	 * 取得节点的值
	 * */
	public String getNodeValue(StringBuffer inputStrb,String nodetree){
		String nodevalue="";
		try{
			SAXReader saxReader=new SAXReader();
			Document doc=saxReader.read(new InputSource(new StringReader(inputStrb.toString())));
			
			List treeList=doc.selectNodes(nodetree);
			Iterator iter=treeList.iterator();
			while(iter.hasNext()){
				Element e=(Element)iter.next();
				nodevalue=e.getText();
				//System.out.println("nodevalue:"+nodevalue);
			}
			
		}catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return nodevalue;
	}
	
	/**
	 * 通过命名空间取得节点的值
	 * @param inputStrb XML报文
	 * @param xpath 要取得节点的路径，例如：//soapenv:Header//com:originalAddress//com:platType
	 * @param nsMap 命名空间的值，需要 ns.put("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
	 *                             ns.put("com", "http://www.chinamobile.com/vgop/serviceorder/v1_0/common");
	 * */
	public String getNodeValueOfNS(StringBuffer inputStrb,String xpath,Map nsMap){
		String nodevalue="";
		try{
			SAXReader sr = new SAXReader();
			StringReader strr = new StringReader(inputStrb.toString());
			Document doc = sr.read(strr);
			
			Map ns = nsMap;
			
			XPath x_path = doc.createXPath(xpath);
			x_path.setNamespaceURIs(ns);
			List res = x_path.selectNodes(doc);
			
			//取得节点的值,取第一个节点，可以扩展取第N个节点
			if (res.size() != 0) {
				//for (int i = 0; i < res.size(); i++) {
				Element tmp = (Element) res.get(0);
				//System.out.println("text [" + 0 + "] name: "+ tmp.getText());
				nodevalue = tmp.getText();
				//System.out.println("element[" + 0 + "] name: "+ tmp.getName());
				//System.out.println("element[" + 0 + "] parent name: "+ tmp.getParent().getName());
				//}
			}
			
			
		}catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return nodevalue;
	}
	
	/**
	 * 通过命名空间取得节点的值
	 * @param inputStrb XML报文
	 * @param xpath 要取得节点的路径，例如：//soapenv:Header//com:originalAddress//com:platType
	 * @param nsMap 命名空间的值，需要 ns.put("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
	 *                             ns.put("com", "http://www.chinamobile.com/vgop/serviceorder/v1_0/common");
	 * @param num:要取值得节点数                            
	 * */
	public String getNodeValueOfNSByIndex(StringBuffer inputStrb,String xpath,Map nsMap,int num){
		String nodevalue="";
		//HashMap<String,String> hp = new HashMap<String,String>();
		try{
			SAXReader sr = new SAXReader();
			StringReader strr = new StringReader(inputStrb.toString());
			Document doc = sr.read(strr);
			
			Map ns = nsMap;
			
			XPath x_path = doc.createXPath(xpath);
			x_path.setNamespaceURIs(ns);
			List res = x_path.selectNodes(doc);
			
			//取得节点的值,取第一个节点，可以扩展取第N个节点
			int k = num-1;
			if (res.size() != 0) {
				for (int i = 0; i < res.size(); i++) {
					Element tmp = (Element) res.get(i);
					//System.out.println("text [" + i + "] name: "+ tmp.getText());
					//System.out.println("element[" + i + "] name: "+ tmp.getName());
					if(i == k){
						nodevalue = tmp.getText();
						//System.out.println("===text [" + k + "] name===: "+ nodevalue);
						break;
					}
					//nodevalue = tmp.getText();
					//System.out.println("element[" + i + "] name: "+ tmp.getName());
					//String nodeName = tmp.getName();
					//System.out.println("element[" + 0 + "] parent name: "+ tmp.getParent().getName());
					//hp.put(nodeName, nodevalue);
				}
			}
			
			
		}catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return nodevalue;
	}
	
	public int getNodeTreeElemSize(StringBuffer inputStrb,String nodetree){
		int eSize=0;
		try{
			SAXReader saxReader=new SAXReader();
			Document doc=saxReader.read(new InputSource(new StringReader(inputStrb.toString())));
			
			List treeList=doc.selectNodes(nodetree);
			//Node tree=doc.selectSingleNode(nodetree);
			Iterator iter=treeList.iterator();
			while(iter.hasNext()){
				//	eSize++;
				Element e=(Element)iter.next();
				//System.out.println("XML e.getText():--:"+e.getName());
			}
			
			//System.out.println("XML eSize"+eSize);
		}catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return eSize;
	}
	
	public static void main(String[] args){
		StringBuffer cdataXML = new StringBuffer();
		cdataXML.append("<xml>");
		cdataXML.append("<return_code><![CDATA[SUCCESS]]></return_code>");
		cdataXML.append("<return_msg><![CDATA[OK]]></return_msg>");
		cdataXML.append("<appid><![CDATA[wxc5314564503bb3d5]]></appid>");
		cdataXML.append("<mch_id><![CDATA[1323888701]]></mch_id>");
		cdataXML.append("<nonce_str><![CDATA[jB7S4Cl0uH8BmrP3]]></nonce_str>");
		cdataXML.append("<sign><![CDATA[A267A43F339CC0F70C91A5AFCDE2CAE1]]></sign>");
		cdataXML.append("<result_code><![CDATA[SUCCESS]]></result_code>");
		cdataXML.append("<prepay_id><![CDATA[wx201604151637243e75c2e5340415187030]]></prepay_id>");
		cdataXML.append("<trade_type><![CDATA[APP]]></trade_type>");
		cdataXML.append("</xml>");
		
		ReadXml rx = new ReadXml();
		String retCode = rx.getNodeValue(cdataXML, "/xml/return_code");
		String prepayId = rx.getNodeValue(cdataXML, "/xml/prepay_id");
		System.out.println("retCode:"+retCode);
		System.out.println("retCode:"+prepayId);
	}
	

}
